/**
 * 批量修改大于当前的排序-1
 * @param model    模型
 * @param params    传参  userId,parentId,seq
 * @returns {Promise<object>} 结果
 */
function modifySeq(model, params) {
    return new Promise((resolve, reject) => {
        model.updateMany({
            userId: params.userId,
            parentId: params.parentId,
            seq: {$gt: params.seq}
        }, {$inc: {seq: -1}}, (err, docs) => {
            if (!err) {
                resolve({code: 1, data: null, msg: '修改排序成功'});
            } else {
                reject({code: 0, data: null, msg: err.message});
            }
        })
    })
}

/**
 * 判断菜单是父菜单还是子菜单 true存在 false 不存在
 * @param model    模型
 * @param params        参数 menuId
 * @returns {Promise<boolean>} 结果
 */
function includeChildren(model, params) {
    return new Promise((resolve, reject) => {
        model.find({userId: params.userId, parentId: params.menuId}, {_id: 0, __v: 0}).exec((err, docs) => {
            resolve(!!docs.length);
        })
    })
}

/**
 * 获取seq最大值和最小值
 * @param model    模型
 * @param params    参数 userId parentId
 * @returns {Promise<object>} 结果
 */
function getMenuSeq(model, params) {
    return new Promise((resolve, reject) => {
        const aggregate = [
            {
                $match: {
                    $and: [
                        {userId: params.userId},
                        {parentId: params.parentId || ''}
                    ]
                }
            },
            {
                $group: {
                    _id: null,
                    max: {$max: '$seq'},
                    min: {$min: '$seq'}
                }
            }
        ];
        model.aggregate(aggregate, (err, docs) => {
            resolve({max: docs[0] ? docs[0].max : 0, min: docs[0] ? docs[0].min : 0});
        })
    })
}

/**
 * 获取菜单信息
 * @param model    模型
 * @param params    传参  userId,menuId
 * @returns {Promise<object>}
 */
function getMenuInfo(model, params) {
    return new Promise((resolve, reject) => {
        model.findOne({userId: params.userId, menuId: params.menuId}, {_id: 0, __v: 0}).exec((err, docs) => {
            resolve(docs);
        })
    })
}


/**
 * 修改单个菜单排序
 * @param model    模型
 * @param params    传参  userId,parentId,seq,direction
 * @returns {Promise<object>}
 */
function updateSeq(model, params) {
    return new Promise((resolve, reject) => {
        model.findOneAndUpdate({
            userId: params.userId,
            parentId: params.parentId,
            seq: params.seq - params.direction
        }, {$inc: {seq: params.direction}}, (err, docs) => {
            if (!err) {
                resolve({code: 1, data: null, msg: '修改排序成功'});
            } else {
                reject({code: 0, data: null, msg: err.message});
            }
        })
    })
}

module.exports = {getMenuSeq, includeChildren, modifySeq, getMenuInfo, updateSeq}
